﻿// Author: AustralTek 
// Create date: 2010/05/04
// http://www.australtek.com
// Copyright: 2009 - 2010

(function () {
    function _IndustrialGrid(object, options) {
        try {
            //Private Members            
            var privateParameters = null;
            var loadingContainer;
            var loadingImage;
            var loadingTitle;
            var data;
            var titleContainer = null;

            function _initialize(myDiv, options) {
                try {
                    var uxIGContainer = document.createElement('div');
                    uxIGContainer.className = 'industrialGridContainer';
                    var uxIGHeader = document.createElement('div');
                    uxIGHeader.className = 'IGHeader';
                    var uxIGP = document.createElement('div');
                    uxIGP.className = 'classTitle';
                    uxIGP.innerHTML = (options.Title) ? options.Title : 'Industrial Grid 2.0';
                    uxIGHeader.appendChild(uxIGP);
                    uxIGContainer.appendChild(uxIGHeader);
                    var uxIGTableContainer = document.createElement('div');
                    uxIGTableContainer.className = 'IGTableContainer';
                    uxIGContainer.appendChild(uxIGTableContainer);

                    privateParameters = new PrivateParameters(options);
                    privateParameters.Version.Class = 'IndustrialGrid';
                    privateParameters.Container = uxIGTableContainer;

                    var uxLoadingContainer = document.createElement('div');
                    loadingContainer = uxLoadingContainer;
                    uxLoadingContainer.className = 'loadingContainer';
                    uxLoadingContainer.style.display = 'none';
                    uxIGHeader.appendChild(uxLoadingContainer);

                    var uxLoadingImage = document.createElement('div');
                    uxLoadingImage.className = 'animate';
                    loadingImage = uxLoadingImage;
                    uxLoadingContainer.appendChild(uxLoadingImage);

                    var uxLoadingTitle = document.createElement('div');
                    uxLoadingTitle.className = 'title';
                    loadingTitle = uxLoadingTitle;
                    uxLoadingContainer.appendChild(uxLoadingTitle);
                    uxLoadingTitle.innerHTML = 'Loading...';

                    myDiv.appendChild(uxIGContainer);
                } catch (Error) { privateParameters.Events.onError(Error); }
            };
            function _setLegend(legend, animate) {
                try {
                    loadingTitle.innerHTML = legend;
                    loadingContainer.style.display = '';
                    if ((animate) || (animate.toString().toUpperCase() == 'TRUE')) loadingImage.className = 'animate';
                    else loadingImage.className = 'noAnimate';
                } catch (Error) { privateParameters.Events.onError(Error); }
            };
            function _refreshData(parameters) {
                try {
                    if ((parameters!=undefined)&&(parameters.Legend)) {
                        loadingImage.className = ((parameters.Legend.Animate) || (parameters.Legend.Animate.toString().toUpperCase() == 'TRUE')) ? 'animate' : 'noAnimate';
                        loadingTitle.innerHTML = parameters.Legend.Title;

                    } else {
                        loadingImage.className = 'animate';
                        loadingTitle.innerHTML = 'Loading...';
                    }
                    loadingContainer.style.display = '';
                    var url = privateParameters.URL;
                    var options = {}; options.data = {};
                    options.data.DatabaseParameters = privateParameters.DatabaseParameters;
                    options.data.JSONFile = privateParameters.JSONFile;
                    for (var conParam in privateParameters.ConnectionParameters)
                        options[conParam] = privateParameters.ConnectionParameters[conParam];
                    if ((parameters) && (parameters.Version))
                        options.data.DatabaseParameters.QueryParameters = parameters.GetQueryParameters();
                    else options = (parameters) ? parameters : options;

                    options.data.Namespace = privateParameters.Version.Namespace;
                    options.data.Class = privateParameters.Version.Class;
                    options.onSuccess = function (requestData) {
                        if ((requestData) && (!requestData.message)) {
                            data = requestData;
                            loadingContainer.style.display = 'none';
                            _redraw(privateParameters.Container, data);
                        }
                        else {
                            loadingContainer.style.display = '';
                            loadingTitle.innerHTML = 'No available Data.';
                            loadingImage.className = 'noAnimate';
                            privateParameters.Container.innerHTML = '';
                        }
                    }
                    options.onFailure = function (message) {
                        privateParameters.Events.onFailure(message);
                    }
                    if ((url == undefined) || (url == '')) {
                        if ((privateParameters.JSONStringFile != undefined) && (privateParameters.JSONStringFile != '')) {
                            data = privateParameters.JSONStringFile;
                            loadingContainer.style.display = 'none';
                            _redraw(privateParameters.Container, data);
                        } else {
                            loadingContainer.style.display = '';
                            loadingTitle.innerHTML = 'No available Data.';
                            loadingImage.className = 'noAnimate';
                            privateParameters.Container.innerHTML = '';
                        }
                    }

                    RequestJSON(url, options);
                } catch (Error) { privateParameters.Events.onError(Error); }
            };
            function _redraw(container, data) {
                try {
                    var cols = data.columns | data.fields;
                    var matrix = data.matrix;
                    var metadata = data.metadata;
                    FreeRefManager.RemoveAllChildNodes(container);
                    if ((matrix) && (matrix.length == cols)) { container.innerHTML = '<p style=" font-family:Microsoft Sans Serif ;color:#808080">No available data for selected scope</p>'; return; }
                    else container.style.display = '';
                    table = document.createElement("table");
                    table.className = 'industrialGrid';
                    container.appendChild(table);
                    table.cellPadding = '0';
                    table.cellSpacing = '0';
                    thead = document.createElement("thead");
                    table.appendChild(thead);
                    tbody = document.createElement("tbody");
                    table.appendChild(tbody);
                    trMainHead = document.createElement("tr");
                    thead.appendChild(trMainHead);
                    trSecHead = document.createElement("tr");
                    thead.appendChild(trSecHead);
                    var textValue; var c; var rCols = 0;
                    var firstCellcolspan = null; //firstcell colspan
                    var colFormat = new Array(cols);
                    for (c = 0; c < cols; c++) {
                        colFormat[c] = {};  // object that holds metathis.data for each column
                        textValue = matrix[c];
                        var tvs = textValue.split("!");
                        textValue = tvs[0];
                        colFormat[c].columnName = textValue;
                        for (k = 1; k < tvs.length; k++) {
                            if (tvs[k].indexOf('ns') != -1) colFormat[c].noShow = true;  // !ns indicates NO SHOW: don'data show the column
                            if (tvs[k].indexOf('he') != -1) colFormat[c].isHeader = true;  // !he indicates header: show it with header style
                            if (tvs[k].indexOf('rs') != -1) colFormat[c].rowSpan = true;  // !rs indicates ROWSPAN: join together cells with same values
                            if (tvs[k].indexOf('ac') != -1) colFormat[c].alignCenter = true; // !ac indicates ALIGN CENTER
                            if (tvs[k].indexOf('al') != -1) colFormat[c].alignLeft = true; // !al indicates ALIGN LEFT
                            else colFormat[c].colSpan = false;
                        }
                        if (colFormat[c].noShow) continue; // does not print !ns columns (ns = no show)
                        rCols++;
                        if (textValue.indexOf('@') == -1) {
                            td = document.createElement("td");
                            td.className = 'header';
                            trMainHead.appendChild(td);
                            if (colFormat[c].fixedWidth) td.style.width = colFormat[c].fixedWidth + '%'
                            td.rowSpan = 2;
                            td.innerHTML = textValue;
                            colFormat[c].headerPointerTop = td;
                            colFormat[c].headerPointer = td;
                        } else {
                            td = document.createElement("td");
                            td.className = 'header';
                            td.innerHTML = textValue.substring(0, textValue.indexOf('@'));
                            if (firstCellcolspan != null && firstCellcolspan.innerHTML == td.innerHTML) firstCellcolspan.colSpan += 1;
                            else {
                                firstCellcolspan = td;
                                firstCellcolspan.colSpan = 1;
                                trMainHead.appendChild(td);
                            }
                            colFormat[c].headerPointerTop = td;
                            td = document.createElement("td");
                            td.className = 'header';
                            trSecHead.appendChild(td);
                            td.innerHTML = textValue.substring(textValue.indexOf('@') + 1);
                            colFormat[c].headerPointer = td;
                        }
                    }
                    for (r = 1; r < matrix.length / cols; r++) { // break array into matrix for filling this.data
                        var tr = document.createElement("tr");
                        var hasFooter = false; var firstPar = true;
                        tbody.appendChild(tr);
                        tr.id = r;
                        if ((r + 1) % 2 == 1) tr.className = 'odd';
                        else tr.className = 'par';
                        var hlinkCtr = 0; // header counter and to prevent from reading the entire row
                        for (c = 0; c < cols; c++) {
                            td = document.createElement("td");
                            if (matrix[r * cols + c]) td.innerHTML = matrix[r * cols + c];  // if it is not undefined/null set the value
                            else td.innerHTML = '&nbsp;'
                            if (colFormat[c].alignCenter || !_isNumber(matrix[r * cols + c])) td.style.textAlign = 'center';
                            if (colFormat[c].alignLeft) td.style.textAlign = 'left';
                            if (colFormat[c].isHeader) td.className += ' header'; else td.className += 'normal';
                            /* Check if the cell has some metadata value*/
                            if (metadata && metadata[r - 1] && metadata[r - 1][colFormat[c].columnName] && metadata[r - 1][colFormat[c].columnName] != '') {
                                var s = metadata[r - 1][colFormat[c].columnName];
                                var aq;
                                try { aq = s.split("!"); }
                                catch (ex) { }
                                if (aq) td.className += ' ' + aq[0];  // set the classnames (Errors, Process Problems or Warnings)
                                if (aq && aq.length > 1) td.title = aq[1];    // set the tooltip text if any
                                if (aq && aq[0] == 'E') td.innerHTML += '*';
                            }
                            if (colFormat[c].rowSpan && colFormat[c].fcrs != undefined) colFormat[c].fcrs.className += ' nohover'; //check column name                                                     
                            if (colFormat[c].rowSpan && colFormat[c].fcrs != undefined && colFormat[c].fcrs.innerHTML == td.innerHTML) colFormat[c].fcrs.rowSpan += 1; //check column name 
                            else if (colFormat[c].noShow) { /* do not add the cell */ }
                            else if (colFormat[c].colSpan && hasFooter) { /*do not add the cell footer*/ }
                            else {
                                colFormat[c].fcrs = td;
                                tr.appendChild(td);
                                /* set counter to the number of colspan */
                                if ((hasFooter) && (td.colSpan > 1)) c = td.colSpan;
                            }
                        }
                    }
                    var legend;
                    legend = document.createElement('tr');
                    tbody.appendChild(legend);
                    td = document.createElement('td');
                    legend.appendChild(td);
                    td.className = 'legend';
                    if (rCols > 2) td.colSpan = rCols - 2;
                    td.innerHTML = '&nbsp;'
                    if (metadata) {
                        td.innerHTML = '<label class=warning>999</label> Warnings &nbsp; &nbsp;';
                        td.innerHTML += '<label class=problem>999</label> Process Problems &nbsp; &nbsp;';
                        td.innerHTML += '<label class=error>999*</label> Errors &nbsp; &nbsp;';
                    }
                    td.style.textAlign = 'left';
                    td.style.borderRight = 'none';
                    td = document.createElement('td');
                    td.colSpan = 2;  // uses 2 columns
                    legend.appendChild(td);
                    td.className = 'legend';
                    td.style.textAlign = 'right';
                    //td.innerHTML = '&nbsp;<a href=#top> go to Top </a>';
                } catch (Error) { privateParameters.Events.onError(Error); }
            };
            function _isNumber(value) {
                return isFinite((value * 1.0));
            };
            _initialize(object, options);

            /*--------------------------*/
            /*------Public members------*/
            /*--------------------------*/
            this.SetLegend = function (legend, animate) { _setLegend(legend, animate); }
            this.SetJSONStringFile = function (string) { if (privateParameters) privateParameters.JSONStringFile = string; };
            this.GetDatabaseEngine = function () { return DatabaseConnection.GetDatabaseEngine(privateParameters.DatabaseEngine); };
            this.SetDatabaseEngine = function (newDatabaseEngine) { DatabaseConnection.SetDatabaseEngine(privateParameters, newDatabaseEngine); };
            this.GetConnectionStringName = function () { return DatabaseConnection.GetConnectionStringName(privateParameters.ConnectionStringName); };
            this.SetConnectionStringName = function (newConnectionStringName) { DatabaseConnection.SetConnectionStringName(privateParameters, newConnectionStringName); };
            this.GetTablesCount = function () { return DatabaseConnection.GetTablesCount(privateParameters.TablesCount); };
            this.SetTablesCount = function (newTablesCount) { DatabaseConnection.SetTablesCount(privateParameters, newTablesCount); };
            this.GetProcedure = function () { return DatabaseConnection.GetProcedure(privateParameters.Procedure); };
            this.SetProcedure = function (newProcedure) { DatabaseConnection.SetProcedure(privateParameters, newProcedure); };
            this.RefreshData = function (parameters) {
                try {
                    _refreshData(parameters);
                } catch (Error) { privateParameters.Events.onError(Error); return Error; }
            };
        } catch (Error) { }
    }
    window.IndustrialGrid = function (object, options) { return new _IndustrialGrid(object, options); }
})();